<template>
  <div>
    <div style="height: 542px">
      <div
        style="
          display: flex;
          justify-content: space-between;
          align-items: center;
        "
      >
        <div
          style="
            font-weight: 500;
            font-size: 18px;
            color: #222b3c;
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 0px 16px;
          "
        >
          <div>新增计算公式</div>
          <div style="font-weight: 400; font-size: 14px; color: #97999c">
            使用数学运算符编辑公式
          </div>
        </div>
        <div>
          <svg
            style="color: #97999c; font-size: 14px; cursor: pointer"
            class="icon"
            aria-hidden="true"
            @click="cancel"
          >
            <use xlink:href="#icon-cuowu"></use>
          </svg>
        </div>
      </div>
      <div style="height: 440px; margin: 12px 0px">
        <div
          style="
            width: 100%;
            height: 180px;
            border: 1px solid #dedfe3;
            border-radius: 8px;
            background: #ffffff;
            margin-bottom: 11px;
          "
        >
          <div
            class="scroll-container"
            style="
              padding: 12px;
              height: 142px;
              display: flex;
              flex-wrap: wrap;
              gap: 4px;
            "
          >
            <draggable
              style="
                padding: 12px;
                height: 118px;
                display: flex;
                flex-wrap: wrap;
                gap: 8px 4px;
                align-content: flex-start;
                cursor: move;
              "
              id="targetDiv"
              v-model="variablePool"
              v-bind="{ sort: true, forceFallback: true }"
              item-key="id"
              handle=".handle"
              animation="300"
              :move="onMove"
              ghost-class="ghostClass"
              group="variables"
            >
              <div
                class="handle"
                v-for="(item, index) in variablePool"
                :key="index"
              >
                <div
                  class="tag"
                  v-if="
                    ['LogicalOperations', 'NumericOperators'].includes(
                      item.type
                    )
                  "
                  style="
                    position: relative;
                    display: inline;
                    height: 26px;
                    background: #e8f2ff;
                    border-radius: 6px;
                    padding: 3px 8px;
                  "
                >
                  {{ item.key }}
                  <svg
                    class="icon tagSvg"
                    @click="variablePool.splice(index, 1)"
                    style="
                      position: absolute;
                      font-size: 14px;
                      color: red;
                      top: -5px;
                      right: -5px;
                    "
                    aria-hidden="true"
                  >
                    <use xlink:href="#icon-zhongbiaojieguo-buzhongbiao"></use>
                  </svg>
                </div>
                <div
                  class="tag"
                  v-else-if="item.type === 'variable'"
                  style="
                    position: relative;
                    display: inline;
                    height: 26px;
                    background: #ffffff;
                    border-radius: 6px;
                    border: 1px solid #e7e9f1;
                    padding: 3px 8px;
                  "
                >
                  {{ item.key }}
                  <svg
                    class="icon tagSvg"
                    @click="variablePool.splice(index, 1)"
                    style="
                      position: absolute;
                      font-size: 14px;
                      color: red;
                      top: -5px;
                      right: -5px;
                    "
                    aria-hidden="true"
                  >
                    <use xlink:href="#icon-zhongbiaojieguo-buzhongbiao"></use>
                  </svg>
                </div>
                <div
                  class="tag"
                  v-else-if="item.type === 'constant'"
                  style="
                    position: relative;
                    display: inline;
                    height: 26px;
                    background: #fafbfd;
                    border-radius: 6px;
                    border: 1px solid #dedfe3;
                    padding: 3px 8px;
                  "
                >
                  {{ item.key }}
                  <svg
                    class="icon tagSvg"
                    @click="variablePool.splice(index, 1)"
                    style="
                      position: absolute;
                      font-size: 14px;
                      color: red;
                      top: -5px;
                      right: -5px;
                    "
                    aria-hidden="true"
                  >
                    <use xlink:href="#icon-zhongbiaojieguo-buzhongbiao"></use>
                  </svg>
                </div>
              </div>
            </draggable>
          </div>
          <div
            style="
              width: 100%;
              height: 36px;
              padding: 8px 11px;
              display: flex;
              background: #fafbfd;
              border-radius: 0px 0px 8px 8px;
            "
          >
            <div style="font-weight: 400; font-size: 14px; color: #54607c">
              公式预览：
            </div>
            <div
              style="
                font-weight: 400;
                font-size: 14px;
                color: #222b3c;
                height: 20px;
                width: 666px;
              "
            >
              <!-- {{ preview }} -->
              <OverflowText
                style="font-weight: 500"
                :text="preview"
                :maxWidth="'650px'"
              />
            </div>
            <div>
              <a-button
                class="clearStyle"
                type="link"
                @click="variablePool = []"
              >
                清空
              </a-button>
            </div>
          </div>
        </div>
        <div
          style="
            width: 100%;
            height: 250px;
            border: 1px solid #dedfe3;
            border-radius: 8px;
            background: #ffffff;
            display: flex;
          "
        >
          <div
            style="
              width: 200px;
              background: #f7f9fd;
              height: 100%;
              padding: 12px;
              border-radius: 8px;
            "
          >
            <div
              style="
                color: #515665;
                font-size: 14px;
                font-weight: 500;
                margin-bottom: 7px;
              "
            >
              运算符号
            </div>
            <div>
              <draggable
                style="overflow: hidden"
                v-model="OperatorEnum"
                v-bind="{
                  group: { name: 'variables', pull: 'clone' },
                  sort: true,
                  forceFallback: true,
                }"
                animation="300"
                :move="onMove"
                handle=".handle"
                drag-class="dragClass"
                :clone="onClone"
                @start="onDragStart"
                @end="onDragEnd"
              >
                <div
                  v-for="(item, index) in OperatorEnum"
                  @click="variablePool.push(item)"
                  :key="index"
                  class="Enum"
                  style="
                    position: relative;
                    cursor: pointer;
                    float: left;
                    margin: 3px;
                    background: #ffffff;
                    border-radius: 8px;
                    border: 1px solid #e7e9f1;
                    font-size: 14px;
                    padding: 7px 14px;
                    text-align: center;
                  "
                >
                  <!-- class="handle"  -->
                  <div style="width: 8px; height: 21px">
                    {{ item.key }}
                  </div>
                  <svg
                    class="handle icon EnumSvg"
                    style="
                      position: absolute;
                      cursor: move;
                      font-size: 14px;
                      top: 0px;
                      left: 0px;
                    "
                    aria-hidden="true"
                  >
                    <use xlink:href="#icon-shangxiatuozhuai"></use>
                  </svg>
                </div>
              </draggable>
            </div>
            <div style="margin-top: 50px">
              <div
                style="
                  font-weight: 400;
                  color: #b5b8bf;
                  font-size: 12px;
                  margin-bottom: 5px;
                "
              >
                三元运算符
              </div>
              <div>
                <draggable
                  v-model="triple"
                  v-bind="{
                    group: { name: 'variables', pull: 'clone' },
                    sort: true,
                    forceFallback: true,
                  }"
                  animation="300"
                  :move="onMove"
                  handle=".handle"
                  drag-class="dragClass"
                  :clone="onClone"
                  @start="onDragStart"
                  @end="onDragEnd"
                >
                  <div
                    v-for="(item, index) in triple"
                    @click="variablePool.push(item)"
                    :key="index"
                    class="Enum"
                    style="
                      position: relative;
                      cursor: pointer;
                      float: left;
                      margin: 3px;
                      background: #ffffff;
                      border-radius: 8px;
                      border: 1px solid #e7e9f1;
                      font-size: 14px;
                      padding: 7px 14px;
                      text-align: center;
                    "
                  >
                    <div style="width: 8px; height: 21px">
                      {{ item.key }}
                    </div>
                    <svg
                      class="handle icon EnumSvg"
                      style="
                        position: absolute;
                        cursor: move;
                        font-size: 14px;
                        top: 0px;
                        left: 0px;
                      "
                      aria-hidden="true"
                    >
                      <use xlink:href="#icon-shangxiatuozhuai"></use>
                    </svg>
                  </div>
                </draggable>
              </div>
            </div>
          </div>
          <div
            style="
              width: 376px;
              height: 100%;
              border-left: 1px solid #e7e9f1;
              border-right: 1px solid #e7e9f1;
              padding: 12px;
            "
          >
            <div
              style="
                color: #515665;
                font-size: 14px;
                font-weight: 500;
                margin-bottom: 10px;
              "
            >
              表单变量
            </div>
            <div class="scroll-container" style="height: 200px">
              <draggable
                ref="variable"
                v-model="variableList"
                v-bind="{
                  group: { name: 'variables', pull: 'clone' },
                  sort: true,
                  forceFallback: true,
                }"
                animation="300"
                :move="onMove"
                handle=".handle"
                @start="onDragStart"
                @end="onDragEnd"
                :clone="onClone"
                drag-class="dragClass"
              >
                <div
                  v-for="(item, index) in variableList"
                  @click="variablePool.push(item)"
                  :key="index"
                  style="
                    cursor: pointer;
                    height: 32px;
                    background: #ffffff;
                    border-radius: 6px;
                    border: 1px solid #f0f2f5;
                    padding: 0px 6px;
                    margin-bottom: 4px;
                  "
                >
                  <div style="overflow: hidden">
                    <div
                      style="float: left; margin-right: 6px; line-height: 29px"
                    >
                      <div class="handle">
                        <svg class="icon" aria-hidden="true">
                          <use xlink:href="#icon-shangxiatuozhuai"></use>
                        </svg>
                      </div>
                    </div>
                    <div
                      style="
                        float: left;
                        font-weight: 400;
                        font-size: 14px;
                        color: #223c4d;
                        line-height: 29px;
                      "
                    >
                      {{ item.key }}
                    </div>
                    <div
                      style="
                        float: right;
                        color: #2983ff;
                        font-size: 12px;
                        font-weight: 400;
                        background: #e8f2ff;
                        border-radius: 11px;
                        padding: 2px 7px;
                        margin-top: 4px;
                      "
                    >
                      {{ dataTypeOptions[item.dataType] }}
                    </div>
                  </div>

                  <div style="clear: both"></div>
                  <!-- 清除浮动 -->
                </div>
              </draggable>
            </div>
          </div>
          <div style="padding: 12px; width: 246px">
            <div style="display: flex; justify-content: space-between">
              <div
                style="
                  color: #515665;
                  font-size: 14px;
                  font-weight: 500;
                  margin-bottom: 10px;
                "
              >
                固定值
              </div>
              <div
                style="
                  width: 62px;
                  height: 24px;
                  border-radius: 12px;
                  background: #ffffff;
                  border: 1px solid #dedfe3;
                  font-size: 12px;
                  font-weight: 400;
                  color: #646a73;
                  padding: 2px 9px;
                  display: flex;
                  justify-content: space-between;
                  align-items: center;
                "
              >
                <div>录入</div>
                <svg class="icon" aria-hidden="true">
                  <use xlink:href="#icon-huiche"></use>
                </svg>
              </div>
            </div>
            <div class="scroll-container" style="height: 200px">
              <div style="margin-bottom: 16px; display: flex">
                <draggable
                  style="
                    background: #f7f8fa;
                    height: 32px;
                    border-radius: 4px 0px 0px 4px;
                    padding: 6px 3px;
                  "
                  v-model="constantList"
                  v-bind="{
                    group: { name: 'variables', pull: 'clone' },
                    sort: true,
                    forceFallback: true,
                  }"
                  animation="300"
                  :move="onMove"
                  @start="onDragStart"
                  @end="onDragEnd"
                  :clone="onClone"
                  drag-class="dragClass"
                >
                  <div>
                    <div class="handle">
                      <svg style="width: 15px" class="icon" aria-hidden="true">
                        <use xlink:href="#icon-shangxiatuozhuai"></use>
                      </svg>
                    </div>
                  </div>
                </draggable>
                <div>
                  <a-input
                    style="width: 200px"
                    v-model="constantVal"
                    @keydown.enter="handleEnterPress"
                  ></a-input>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div style="display: flex; justify-content: space-between; gap: 0px 8px">
        <div
          @click="$refs.vuedraggable.open(variablePool)"
          style="
            cursor: pointer;
            background: #ffffff;
            border-radius: 4px;
            border: 1px solid #2983ff;
            color: #2983ff;
            line-height: 30px;
            padding: 0px 15px;
          "
        >
          <!-- 图标得换 -->
          <svg
            style="color: #2983ff; font-size: 14px"
            class="icon"
            aria-hidden="true"
          >
            <use xlink:href="#icon-cuowu"></use>
          </svg>
          验证公式
        </div>
        <div>
          <a-button style="margin-right: 10px" @click="cancel"> 取消 </a-button>
          <!-- handleOk -->
          <a-button type="primary" @click="handleOk"> 确定 </a-button>
        </div>
      </div>
    </div>
    <!-- <img id="drag-icon" src="@/assets/kong.png" style="display: none" /> -->
    <formulaVerify ref="vuedraggable" />
  </div>
</template>
<script>
import draggable from "vuedraggable";
import formulaVerify from "@/components/Form/verification/formulaVerify.vue";

import OverflowText from "@/views/dashboard/OverflowText.vue";
import { dataTypeOptions } from "@/components/Form/base/options";

export default {
  name: "Formula",
  components: {
    draggable,
    formulaVerify,
    OverflowText,
  },
  data() {
    return {
      variableName: "变量1", // 要拖拽的变量
      selectEdItem: undefined, // 正在拖着的数据
      originalContents: undefined, // 用于存储原始的元素内容
      dataTypeOptions: dataTypeOptions.reduce((acc, item) => {
        acc[item.value] = item.label;
        return acc;
      }, {}), // 字段类型
      variablePool: [
        // {
        //   key: '+',
        //   value: '1', // 自定义值
        //   type: 'NumericOperators'
        // },
        // {
        //   key: '-',
        //   value: '2', // 自定义值
        //   type: 'NumericOperators'
        // }
      ], // 变量池
      dragging: false, // 标记是否正在拖拽
      constantVal: "", // 手填输入框的值
      preview: "", // 公式预览
      OperatorEnum: [
        {
          key: "+",
          value: "1", // 自定义值
          type: "NumericOperators",
        },
        {
          key: "-",
          value: "2", // 自定义值
          type: "NumericOperators",
        },
        {
          key: "×",
          value: "3",
          type: "NumericOperators",
        },
        {
          key: "÷",
          value: "4",
          type: "NumericOperators",
        },
        {
          key: "(",
          value: "5",
          type: "NumericOperators",
        },
        {
          key: ")",
          value: "6",
          type: "NumericOperators",
        },
        {
          key: "<",
          value: "7",
          type: "NumericOperators",
        },
        {
          key: ">",
          value: "8",
          type: "NumericOperators",
        },
      ],
      triple: [
        {
          key: "?",
          value: "9", // 自定义值，可以替换为实际需求
          type: "LogicalOperations",
        },
        {
          key: ":",
          value: "10",
          type: "LogicalOperations",
        },
        {
          key: "=",
          value: "11",
          type: "LogicalOperations",
        },
      ],
      // variableList: [
      // {
      //   key: '变量A',
      //   value: '1',
      //   dataType: 'string',
      //   type: 'variable'
      // }
      // ],
      constantList: [
        {
          key: "",
          value: "",
          type: "constant",
        },
      ],
    };
  },
  props: {
    formula: {
      type: Array,
      default: () => [],
    },
    variableList: {
      type: Array,
      default: () => [],
    },
  },
  mounted() {
    this.variablePool = this.formula;
    this.previewAdd();
  },
  methods: {
    showModal() {
      // this.visible = true
    },
    cancel(e) {
      console.log(e);
      // this.visible = false
      this.$emit("cancel", { message: "Hello from child" });
    },
    handleOk(e) {
      console.log(e);
      // this.visible = false
      this.$emit("ok", this.variablePool);
    },
    getStyle(type) {
      switch (type) {
        case "LogicalOperations":
        case "NumericOperators":
          return {
            "margin-top": "6px",
            "font-size": "14px",
            background: "#E8F2FF",
            "border-radius": "6px !important",
            padding: "3px 8px",
            color: "#223C4D",
          };
        case "variable":
          return {
            background: "#FFFFFF",
            border: "1px solid #E7E9F1",
            "border-radius": "6px !important",
            padding: "3px 8px",
            color: "#223C4D",
          };
        default:
          return {
            display: "inline-block",
            height: "24px",
            background: "#FAFBFD",
            border: "1px solid #DEDFE3",
            "border-radius": "6px !important",
            padding: "0px 8px",
            margin: "0px",
            color: "#223C4D",
            "font-size": "14px",
            "font-weight": "400",
          };
      }
    },
    onClone(evt) {
      // 这里的 evt 是原始的拖拽事件
      this.selectEdItem = evt; // 克隆的元素
    },
    onDragStart(evt) {
      // 拖拽开始时修改 DOM 结构，或隐藏元素
      // evt.stopPropagation()
      window.getSelection().removeAllRanges();
      document.body.style.cursor = "move";
      const childElements = document.querySelectorAll(".dragClass");
      childElements.forEach((child) => {
        this.originalContents = child.innerHTML;
        const style = this.getStyle(this.selectEdItem.type);
        child.innerHTML = `<div style="display: inline;height: 26px;${Object.entries(
          style
        )
          .map(([key, value]) => `${key}:${value}`)
          .join(";")}">${this.selectEdItem.key}</div>`;
      });
    },
    onMove(evt) {
      window.getSelection().removeAllRanges();
      this.$nextTick(() => {
        const childElements = document.querySelectorAll(".ghostClass");
        childElements.forEach((child) => {
          const style = this.getStyle(this.selectEdItem.type);
          if (evt.from.id !== "targetDiv") {
            child.innerHTML = `<div style="display: inline;height: 26px;${Object.entries(
              style
            )
              .map(([key, value]) => `${key}:${value}`)
              .join(";")}">${this.selectEdItem.key}</div>`;
          }
        });
      });

      if (evt.to.id === "targetDiv") {
        // 从变量池到变量池，不做处理
        return true;
      } else {
        // 禁止从变量池拖拽到菜单
        return false;
      }
    },
    onDragEnd(evt) {
      // 拖拽结束时恢复 DOM 结构，显示元素
      document.body.style.cursor = "default";
      if (evt.to.id === "targetDiv") {
        evt.item.innerHTML = this.originalContents;
        this.variablePool.splice(evt.newIndex, 0, this.selectEdItem);
      }
    },
    previewAdd() {
      // 生成预览
      let i = "";
      this.variablePool.map((item) => {
        i += item.key;
      });
      this.preview = i;
    },
    handleEnterPress() {
      console.log("回车键按下了，输入的值是：", this.constantVal);
      this.variablePool.push(this.constantList[0]);
      // 你可以在这里处理按下回车键时的逻辑
    },
  },
  watch: {
    variablePool: {
      handler(value) {
        this.previewAdd(value);
      },
      deep: true,
    },
    constantVal: {
      handler(value) {
        console.log(value, "iiiiii");
        this.constantList[0] = {
          ...this.constantList[0],
          value: value,
          key: value,
        };
      },
      deep: true,
    },
  },
};
</script>
<style lang="less" scoped>
/deep/ .arco-modal {
  border-radius: 16px;
}

/deep/ .arco-modal-body {
  padding: 9px 24px;
}

/deep/ .arco-radio {
  margin-right: 0px;
}

/deep/ .arco-input-group-addbefore {
  padding: 0px 4px;
  border-radius: 6px 0px 0px 6px;
}

/deep/ .arco-input-group .arco-input-wrapper:last-child .arco-input {
  border-radius: 0px 6px 6px 0px;
}

.scroll-container {
  overflow-x: auto; /* 禁用横向滚动条 */
  overflow-y: auto; /* 允许纵向滚动条 */
  // overflow-x: hidden;  /* 禁用横向滚动条 */
}

.scroll-container::-webkit-scrollbar {
  width: 8px; /* 定义滚动条宽度 */
  height: 8px; /* 定义横向滚动条高度 */
}

.scroll-container::-webkit-scrollbar-thumb {
  background: #bcbdbe; /* 滚动条颜色，可调整 */
  border-radius: 999px; /* 滚动条圆角 */
}

.scroll-container::-webkit-scrollbar-track {
  display: none; /* 隐藏滚动槽 */
}

.clearStyle {
  height: 20px;
  font-weight: 400;
  font-size: 14px;
  color: #515665;
  line-height: 20px;
  text-decoration: underline;
  transition: text-decoration-color 0.3s ease;
}

.clearStyle:hover {
  color: #b1b6c8;
}
// .icon{
//   cursor: pointer
// }

.handle {
  cursor: move;
}

.ghostClass {
  cursor: move !important;
  border: none !important;
  background: none !important;
  margin: 0px !important;
  padding: 0px !important;
}
.dragClass {
  cursor: move !important;
  border: none !important;
  background: none !important;
  margin: 0px !important;
  padding: 0px !important;
}

.tag .tagSvg {
  visibility: hidden; /* 默认隐藏图标 */
  opacity: 0; /* 默认透明 */
  transition:
    opacity 0.3s ease,
    visibility 0s 0.3s; /* 平滑过渡效果 */
}

.tag:hover .tagSvg {
  cursor: pointer;
  visibility: visible; /* 悬停时显示图标 */
  opacity: 1; /* 悬停时使图标不透明 */
  transition:
    opacity 0.3s ease,
    visibility 0s 0s; /* 悬停时过渡到可见 */
}

.Enum .EnumSvg {
  visibility: hidden; /* 默认隐藏图标 */
  opacity: 0; /* 默认透明 */
  transition:
    opacity 0.3s ease,
    visibility 0s 0.3s; /* 平滑过渡效果 */
}

.Enum:hover .EnumSvg {
  cursor: pointer;
  visibility: visible; /* 悬停时显示图标 */
  opacity: 1; /* 悬停时使图标不透明 */
  transition:
    opacity 0.3s ease,
    visibility 0s 0s; /* 悬停时过渡到可见 */
}
</style>
